package leetcode.code0846;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

/**
 * 执行用时：9 ms, 在所有 Java 提交中击败了98.48%的用户
 *
 * 内存消耗：39.2 MB, 在所有 Java 提交中击败了73.33%的用户
 *
 * 通过测试用例：73 / 73
 */
public class Solution implements IDebug {

	public boolean isNStraightHand(int[] hand, int groupSize) {
		int len = hand.length;
		Arrays.sort(hand);
		int range = -1;
		int[] hash0 = new int[len];
		int[] hash1 = new int[len];
		for (int i = 0; i < len; i++) {
			int num = hand[i];
			if (range != -1 && num == hash0[range]) {
				hash1[range] += 1;
			} else {
				hash0[++range] = num;
				hash1[range] = 1;
			}
		}
		range += 1;
		if (groupSize > range) {
			return false;
		}
		int[] help = new int[range];
		help[0] += -hash1[0];
		help[groupSize - 1] += hash1[0];
		int sum = help[0];
		int num = hash0[0];
		for (int i = 1; i < range; i++) {
			int cur = hash0[i];// 数字
			int sub = hash1[i];// 个数
			if (sum != 0 && num + 1 != cur) {// 这句话的意思是要保持连续，前一个数字 == 当前数字才行
				return false;
			}
			num = cur;
			int diff = sum + sub;
			if (diff != 0) {
				help[i] += -diff;
				if (i + groupSize - 1 >= range) {
					return false;
				}
				help[i + groupSize - 1] += diff;
			}
			sum += help[i];
		}
		return true;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[5,1]"), 1));

	}

	public void debug6() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[3,4,5]"), 3));

	}

	public void debug5() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,1,2,2,3,3]"), 4));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,4,5]"), 4));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3(
				"[233722108,386144634,221638886,175028874,408337082,91410299,793763682,972910825,627251147,135020779]"),
				2));

	}

	@Override
	public void debug4() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,6,2,3,4,7,8]"), 3));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug6();
		so.debug5();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
